import axios from 'axios';
import qs from 'qs';
import store from '../store';
import { commonConfig } from '../utils/config';
import bus from '../utils/bus'

const requestArr = [];

axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
});

axios.interceptors.response.use(data => {
  let msg = '网络错误';
  if (data.config.data) {
    console.log(data.config.data)
  } else if (data.config.params){
    console.log(data.config.params)
  }
  if (data && data.data && !data.data.success) {
    alert(data.data.message || '操作失败');
  }
  return data;
}, error => {
  let msg = '网络错误';
  if (error.config && error.config.data) {
    return Promise.reject(error);
  }
});



export function requestAll(fn) {
  return new Promise((resolve, reject) => {
    axios.all(fn)
      .then(axios.spread(function() {
        resolve(arguments)
      }))
  })
}


export function myRequest(apiUrl = '', params, config = {}) { // type = 'post', routeCancel = false, httpType = 'urlTajax', isFullUrl = false,port=19201
  if (!config.hideLoading) {
    requestArr.push(apiUrl);
    bus.$emit('loading-show');
  }
  params = params || {};
  let type = config.type || 'post';
  let url = commonConfig[commonConfig.type].apiBaseUrl + apiUrl;
  return new Promise((resolve, reject) => {
    let requestHeaders = config.requestHeaders;
    let httpParam = qs.stringify(params);
    if (type !== 'post') {
      httpParam = {
        params: params
      }
    }
    if (requestHeaders) {
      httpParam = params
    }
    let axiosConfig = {};
    if (type === 'post') {
      axiosConfig.headers = requestHeaders;
    }
    if (type === 'get') {
      axiosConfig.headers = requestHeaders;
    }
    if (type === 'upload') {
      axiosConfig.headers = {'Content-Type': 'multipart/form-data'};
      type = 'post';
      httpParam = params
    }
    axios[type](url, httpParam, axiosConfig).then(response => {
      if (!config.hideLoading) {
        requestArr.splice(0, 1);
        if (requestArr.length < 1) {
          bus.$emit('loading-hide');
        }
      }
      if (response) {
        resolve(response.data);
      }
    }).catch(err => {
      reject(err)
    })
  })
}
export function aaa () {

}
